from  utils.global_log import logger
import json
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import time
import os


def webdriver_chrome():
    
    chrome_path=os.path.join(os.getcwd() , "chromedriver.exe")
    
    options= webdriver.ChromeOptions()
    
    # 去掉"Chrome正在受到自动化测试软件的控制"
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    
    # 忽略错误
    options.add_argument('--log-level=1') 

    # 设置默认编码为 utf-8
    options.add_argument('lang=zh_CN.UTF-8')

    # 忽略证书错误
    options.add_argument('--ignore-certificate-errors')  

    # 指定用户客户端-模拟手机浏览
    #options.add_argument('user-agent="MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1"')

    # 禁用图片加载
    options.add_argument('blink-settings=imagesEnabled=false')

    # 隐身模式
    ##options.add_argument('incognito')

    # 禁用gpu渲染
    ##options.add_argument('disable-gpu')

    # 全屏启动
    #options.add_argument('start-fullscreen')

    # 全屏启动，无地址栏
    ##options.add_argument('kiosk') 

    # 设置窗口尺寸，注意宽高之间使用逗号而不是x
    #options.add_argument('window-size=1920,1080')

    # 无界面启动，也可以直接设置options.headless=True
    # 与window-size配合使用，否则影响动态滚动
    #options.add_argument('headless')
    
    # 启动时，不激活（前置）窗口【只启动服务】
    #options.add_argument('no-startup-window')

    # 支持调度devtools的performance能力"
    
    # dcaps = {
    #     'browserName': 'chrome',
    #     'goog:loggingPrefs': {
    #         'browser': 'ALL',
    #         'driver': 'ALL',
    #         'performance': 'ALL',
    #     },
    #     'goog:chromeOptions': {
    #         'perfLoggingPrefs': {
    #             'enableNetwork': True,
    #         },
    #         'w3c': False,
    #     },
    # }
    dcaps=DesiredCapabilities.CHROME
    dcaps['goog:loggingPrefs']= {'driver': 'ALL','performance': 'ALL'}
    dcaps['goog:chromeOptions']= {'enableNetwork': True}
    options.add_experimental_option("perfLoggingPrefs", {
                'enableNetwork': True,
            })

    chromeWebDriver=webdriver.Chrome(executable_path=chrome_path,chrome_options=options,desired_capabilities=dcaps)
    #隐式等待(implicit)5秒
    chromeWebDriver.implicitly_wait(3)
    #显示等待(explicit)

    return chromeWebDriver


def get_responseBody(driver:webdriver,url:str):
    '''
    获取接口数据
    参考：https://blog.csdn.net/mxdzchallpp/article/details/106475193
    '''
    performance_log = driver.get_log('performance')

    for entry in performance_log:
        message = json.loads(entry.get('message'))
        message = message['message']['params']
        request = message.get('request')
        
        if(request is not None and request.get('url') == url):  
            #通过requestId获取接口内容     
            content = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': message['requestId']})
            return content
def windows_scrollBy(driver:webdriver,x_pixels:int=0,y_pixels:int=0):
    '''
    js.executeScript(window.scrollBy(x-pixels,y-pixels));
    js.executeScript("arguments[0].scrollIntoView();", Element);
    '''
    
    driver.execute_script(f"window.scrollBy({x_pixels},{y_pixels})") 
    
 
def action_scrollBy(driver:webdriver,elenment):
    action = ActionChains(driver)
    if elenment is not None:
        action.move_to_element(elenment)
    action.send_keys(Keys.PAGE_DOWN).perform()

if __name__=='__main__':
    driver=webdriver_chrome()
    driver.get('https://www.cnblogs.com/ytkah')

    url="https://www.cnblogs.com/ytkah/ajax/GetPostStat"
    content=get_responseBody(driver,url)
    logger.info(f"get [{url}] ResponseBody is:\r\n{ content}") 
    
    title_eles=driver.find_elements(By.XPATH,"//*[@id='mainContent']//div[@class='day']")
    for title_ele in title_eles:
        dayTitle_textContent=title_ele.find_element(By.XPATH,"./div[@class='dayTitle']").get_attribute("textContent")
        logger.info(f"dayTitle_textContent：{dayTitle_textContent}")
        postTitle_innerText=title_ele.find_element(By.XPATH,"./div[@class='postTitle']").get_attribute("innerText")
        logger.info(f"postTitle_innerText:{postTitle_innerText}")
        postCon_innerHTML=title_ele.find_element(By.XPATH,"./div[@class='postCon']").get_attribute("innerHTML")
        logger.info(f"postCon_innerHTML:{postCon_innerHTML}")
        break
    
    clientHeight = driver.execute_script('return document.body.clientHeight')
    logger.info(f"clientHeight:{clientHeight}")
    
    action_scrollBy(driver)
    time.sleep(1)
    windows_scrollBy(driver,0,clientHeight)
    time.sleep(1)
    driver.close()

